package com.carkeeper.filter;

import com.carkeeper.config.SkipConfig;
import com.carkeeper.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;

/**
 * @version : 1.0
 * @outhor : zwk
 * @data : Create in 2020-06-05
 * @description :
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private SkipConfig skipConfig;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取响应
        ServerHttpResponse response = exchange.getResponse();
        //2. 从请求中获取用户访问的uri路径
        String path = request.getURI().getPath();
        boolean matchUrl = Arrays.stream(skipConfig.getUrls())
                .anyMatch(u->path.contains(u));
        //3. 判断如果路径是注册, 登录路径则直接放行
        if(matchUrl){
            return chain.filter(exchange);
        }

//        if (path.contains("")){
//            //放行
//            return chain.filter(exchange);
//        }
        //4. 从请求头中获取jwt令牌
        String authorization = request.getHeaders().getFirst("Authorization");
        String token = authorization.replace("VEA-ADMIN ","");
        //5. 判断jwt令牌获取不到, 报错401, 权限不足
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应
            return response.setComplete();
        }
        try {
            //6. 解析jwt令牌
            JwtUtil.parseJWT(token);

            //7. 正常解析则放行
            return chain.filter(exchange);
        }catch (Exception e){
            log.error("authFilter-error",e);
            //8. 如果解析报错, 则证明jwt令牌被篡改或者超时, 则跑错401权限不足错误
            //设置http返回的响应编码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应
            return  response.setComplete();
        }

    }

    @Override
    public int getOrder() {
        return -100;
    }
}
